package com.jsz.peini.common.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import net.coobird.thumbnailator.Thumbnails;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;

public class FileUtils {
	
	private final static Logger logger =LoggerFactory.getLogger(FileUtils.class);
	
	public static String fileUrl;
	
	//文件上传公共方法
	public static String uploadFile(MultipartFile file,String filePath){
		Calendar now = Calendar.getInstance();
		String returnPath = filePath
	            + now.get(Calendar.YEAR)+"/"+(now.get(Calendar.MONTH)+1)+"/"+now.get(Calendar.DAY_OF_MONTH)+"/";
		
		String fileName = file.getOriginalFilename();
		String extensionName = fileName
				.substring(fileName.lastIndexOf(".") + 1);
		/*newFileName = String.valueOf(System.currentTimeMillis()) + "."
				+ extensionName;*/
		String newFileName = UUID.randomUUID().toString().replace("-", "") + "."
				+ extensionName;
		
		String smallName = UUID.randomUUID().toString().replace("-", "") + "_small."
				+ extensionName;
		
		//String smallPath = returnPath + smallName;
		
		returnPath += newFileName;
		
		UploadQN qn = new UploadQN();
		try {
			qn.upload(file, returnPath);
			
			//getImageFormatName(file, smallPath);
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		}
		
        
		return returnPath+"";
	}
	
	public static String uploadSquareFile(HttpServletRequest request,MultipartFile file,String filePath){
		Calendar now = Calendar.getInstance();
		String returnPath = filePath + now.get(Calendar.YEAR)+"/"+(now.get(Calendar.MONTH)+1)+"/"+now.get(Calendar.DAY_OF_MONTH)+"/";
		
		String fileName = file.getOriginalFilename();
		String extensionName = fileName
				.substring(fileName.lastIndexOf(".") + 1);
		
		String newFileName = UUID.randomUUID().toString().replace("-", "") + "."
				+ extensionName;
		
		returnPath += newFileName;
			
		/*SmallImgVo imgVo = new SmallImgVo();
		imgVo.setBigName(returnPath);
		imgVo.setFile(file);
		RedisUtil.lpush(RedisConstants.IMG_SQUARE_BIG.getBytes(), SerializeUtil.serialize(imgVo));*/
		UploadQN qn = new UploadQN();
		try {
			qn.upload(file, returnPath);
			
			//getImageFormatName(file, smallPath);
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		}
        
		return returnPath;
	}
	
	public static void getImageFormat(MultipartFile bigImg,String smallImgPath,String smallName)throws IOException{
		File fo = new File(smallImgPath); 
		Thumbnails.of(bigImg.getInputStream()).size(350, 350).toFile(smallImgPath);
		UploadQN qn = new UploadQN();
 		try {
 			qn.upload(file2byte(fo), smallName);
 		} catch (IOException e) {
 			logger.error(e.toString());
 			logger.error(e.getMessage(),e);
 		}
	}
	
	public static byte[] file2byte(File file)  
    {  
        byte[] buffer = null;  
        try  
        {  
            //File file = new File(filePath);  
            FileInputStream fis = new FileInputStream(file);  
            ByteArrayOutputStream bos = new ByteArrayOutputStream();  
            byte[] b = new byte[1024];  
            int n;  
            while ((n = fis.read(b)) != -1)  
            {  
                bos.write(b, 0, n);  
            }  
            fis.close();  
            bos.close();  
            buffer = bos.toByteArray();  
        }  
        catch (FileNotFoundException e)  
        {  
            logger.error(e.getMessage(),e);  
        }  
        catch (IOException e)  
        {  
            logger.error(e.getMessage(),e);  
        }  
        return buffer;  
    }  
	
	public static String uploadImgHead(MultipartFile file,String filePath){
		Calendar now = Calendar.getInstance();
		String returnPath = filePath;
		
        try {
    		// 文件保存路径  
            String fileAllPath = fileUrl + returnPath; 
            File filedir = new File(fileAllPath);
            if(!filedir.exists()){
            	filedir.mkdirs();
            }
            // 转存文件  
			file.transferTo(new File(fileAllPath));
			
			File ff = new File(fileAllPath);
			//rotate(ff);
		} catch (IllegalStateException e) {
			logger.error(e.getMessage(),e);
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		}
		return returnPath;
	}

	public static File rotate(File file){
    	try {
    		Metadata metadata = ImageMetadataReader.readMetadata(new FileInputStream(file));

    		for (Directory directory : metadata.getDirectories()) {
    		    for (Tag tag : directory.getTags()) {
    		    	
    		    	String tagName = tag.getTagName();
    		    	String tagDesc = tag.getDescription();
    		    	
    		    	if(tagName.equals("Orientation")){
    		    		BufferedImage src = ImageIO.read(file); 
    		    		int nn = 0;
    		    		if(tagDesc.indexOf("Right side") == 0){
    		    			nn = 90;
    		    		}else if(tagDesc.indexOf("Top, left side") == 0){
    		    			
    		    		}
    		    		
    		            BufferedImage des = RotateImage.Rotate(src, nn);  
    		            ImageIO.write(des,"jpg", new File(file.getPath())); 
    		    	}
    		    	
    		        /*System.out.format("[%s] - %s = %s",
    		            directory.getName(), tag.getTagName(), tag.getDescription());*/
    		    }
    		    if (directory.hasErrors()) {
    		        for (String error : directory.getErrors()) {
    		            System.err.format("ERROR: %s", error);
    		        }
    		    }
    		}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return file;
    }
	
	public static void main(String [] args){
		File file = new File("E:/tomcat7-2/webapps/uploadFiles/upload/square/2017/1/12/a82e610e610a4dc78dbe8250d0c92d24.jpg");
		rotate(file);
	}
}
